﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Entities.PBCM;
using System.Data.SqlClient;
using System.Collections;

namespace WindowsForms.PBCM.usercontrol
{
    public partial class UCThietBi : UserControl
    {
        int iCellHeight, iHeaderHeight;
        double iTotalWidth;
        bool bNewPage, bFirstPage;
        public StringFormat strFormat;
        public ArrayList arrColumnWidths = new ArrayList();
        public ArrayList arrColumnLefts = new ArrayList();
        public int iCount;
        ThietBi da;
        public UCThietBi()
        {

            InitializeComponent();
            dataGridViewThietBi.AutoGenerateColumns = false;
            LoadThietBi(ThietBi.Objects.All().ToList());


        }

        private void LoadThietBi(List<ThietBi> list)
        {
            dataGridViewThietBi.DataSource = list;

        }
        //private void Update(List<ThietBi> list)
        //{
        //    foreach (var s in list)
        //    {
        //        ThietBi.Objects.Update(s);
        //    }

        //}
        //private void Autoupdate()
        //{
        //    List<ThietBi> dt = (List<ThietBi>)dataGridViewThietBi.DataSource;
        //    //SqlCommandBuilder cb = new SqlCommandBuilder(da);
        //    Update(dt);
        //}



        private void dataGridViewThietBi_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            //da = ThietBi.Objects.GetById(dataGridViewThietBi.Rows[e.RowIndex].Cells[0].Value.ToString());
            if (e.RowIndex >= 0)
            {
                if (e.ColumnIndex == 5)
                {
                    if ((int)dataGridViewThietBi.Rows[e.RowIndex].Cells[2].Value == 1 || (int)dataGridViewThietBi.Rows[e.RowIndex].Cells[2].Value == 2)
                    {
                        ThietBi a = new ThietBi();
                        a.MaThietBi = dataGridViewThietBi.Rows[e.RowIndex].Cells[0].Value.ToString();
                        a.TenThietbi = dataGridViewThietBi.Rows[e.RowIndex].Cells[1].Value.ToString();
                        a.TinhTrang = (int)dataGridViewThietBi.Rows[e.RowIndex].Cells[2].Value;
                        a.DonGia = (float)dataGridViewThietBi.Rows[e.RowIndex].Cells[3].Value;
                        try
                        {
                            if (ThietBi.Objects.Update(a))
                            {
                                MessageBox.Show("Sửa thành công");
                                LoadThietBi(ThietBi.Objects.All().ToList());
                            }
                        }

                        catch (Exception)
                        {
                            LoadThietBi(ThietBi.Objects.All().ToList());
                            throw;

                        }
                    }
                    else
                    {
                        MessageBox.Show("Nhap kieu du lieu ko dung");
                        LoadThietBi(ThietBi.Objects.All().ToList());
                    }
                }
                if (e.ColumnIndex == 4)
                {
                    da = ThietBi.Objects.GetById(dataGridViewThietBi.Rows[e.RowIndex].Cells[0].Value.ToString());
                    try
                    {
                        if (ThietBi.Objects.Delete(da))
                        {
                            MessageBox.Show("Xóa thành công");
                            LoadThietBi(ThietBi.Objects.All().ToList());
                        }
                    }

                    catch (Exception)
                    {
                        MessageBox.Show("Xóa thành công");
                        throw;
                    }
                }
            }
        }

        private void buttonXTim_Click(object sender, EventArgs e)
        {
            try
            {
                if (radioButtonMa.Checked == true)
                {
                    List<ThietBi> tam = new List<ThietBi>();
                    tam.Add(ThietBi.Objects.GetById(textBoxXTim.Text));
                    LoadThietBi(tam);
                }
                if (radioButtonTen.Checked == true)
                {
                    LoadThietBi(ThietBi.Objects.Find(x => x.TenThietbi == textBoxXTim.Text).ToList());
                }
                if (radioButtonTinhTrang.Checked == true)
                {
                    LoadThietBi(ThietBi.Objects.Find(x => x.TinhTrang == Convert.ToInt32(textBoxXTim.Text)).ToList());
                }
            }
            catch (Exception)
            {

            }
        }

       

        private void radioButtonMa_CheckedChanged(object sender, EventArgs e)
        {
            textBoxXTim.ResetText();
        }

        private void radioButtonTen_CheckedChanged(object sender, EventArgs e)
        {
            textBoxXTim.ResetText();
        }

        private void radioButtonTinhTrang_CheckedChanged(object sender, EventArgs e)
        {
            textBoxXTim.ResetText();
        }

        private void textBoxXTim_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (radioButtonTinhTrang.Checked == true)
            {
                if (!Char.IsDigit(e.KeyChar) && !Char.IsControl(e.KeyChar))
                    e.Handled = true;
            }
        }

        private void buttonXTim_Click_1(object sender, EventArgs e)
        {
            try
            {
                if (radioButtonMa.Checked == true)
                {
                    List<ThietBi> tam = new List<ThietBi>();
                    tam.Add(ThietBi.Objects.GetById(textBoxXTim.Text));
                    LoadThietBi(tam);
                }
                if (radioButtonTen.Checked == true)
                {
                    LoadThietBi(ThietBi.Objects.Find(x => x.TenThietbi == textBoxXTim.Text).ToList());
                }
                if (radioButtonTinhTrang.Checked == true)
                {
                    LoadThietBi(ThietBi.Objects.Find(x => x.TinhTrang == Convert.ToInt32(textBoxXTim.Text)).ToList());
                }
            }
            catch (Exception)
            {

            }
        }

        private void buttonXIn_Click(object sender, EventArgs e)
        {
            PrintPreviewDialog printDialog = new PrintPreviewDialog();
            printDialog.Document = printDocument1;


            //Get the document

            if (DialogResult.OK == printDialog.ShowDialog())
            {

                printDocument1.DocumentName = "Test Page Print";
                printDocument1.Print();

            }
        }

        private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
        {
            int iRow = 0;


            try
            {
                //Set the left margin
                int iLeftMargin = e.MarginBounds.Left - 25;
                //Set the top margin
                int iTopMargin = e.MarginBounds.Top;
                //Whether more pages have to print or not
                bool bMorePagesToPrint = false;
                int iTmpWidth = 0;
                int iCount = 0;

                //For the first page to print set the cell width and header height
                if (bFirstPage)
                {
                    //foreach (DataGridViewColumn GridCol in dataGridViewtk.Columns)
                    //{
                    //    iTmpWidth = (int)(Math.Floor((double)((double)GridCol.Width /
                    //        (double)iTotalWidth * (double)iTotalWidth *
                    //        ((double)e.MarginBounds.Width / (double)iTotalWidth))));

                    //    iHeaderHeight = (int)(e.Graphics.MeasureString(GridCol.HeaderText,
                    //        GridCol.InheritedStyle.Font, iTmpWidth).Height) + 11;

                    //    // Save width and height of headers
                    //    arrColumnLefts.Add(iLeftMargin);
                    //    arrColumnWidths.Add(iTmpWidth);
                    //    iLeftMargin += iTmpWidth;
                    //}
                    for (int k = 0; k < dataGridViewThietBi.ColumnCount; k++)
                    {


                        iTmpWidth = (int)(Math.Floor((double)((double)dataGridViewThietBi.Columns[k].Width + 15 /
                        (double)iTotalWidth * (double)iTotalWidth *
                        ((double)e.MarginBounds.Width / (double)iTotalWidth))));
                        iTmpWidth = (int)(Math.Floor((double)((double)dataGridViewThietBi.Columns[k].Width /
                            (double)iTotalWidth * (double)iTotalWidth *
                            ((double)e.MarginBounds.Width / (double)iTotalWidth))));

                        iHeaderHeight = (int)(e.Graphics.MeasureString(dataGridViewThietBi.Columns[k].HeaderText,
                            dataGridViewThietBi.Columns[k].InheritedStyle.Font, iTmpWidth).Height) + 11;

                        // Save width and height of headers
                        arrColumnLefts.Add(iLeftMargin);
                        arrColumnWidths.Add(iTmpWidth);
                        iLeftMargin += iTmpWidth;

                    }
                }

                //Loop till all the grid rows not get printed
                while (iRow <= dataGridViewThietBi.Rows.Count - 1)
                {
                    DataGridViewRow GridRow = dataGridViewThietBi.Rows[iRow];
                    //Set the cell height
                    iCellHeight = GridRow.Height + 10;

                    //Check whether the current page settings allows more rows to print
                    if (iTopMargin + iCellHeight >= e.MarginBounds.Height + e.MarginBounds.Top)
                    {
                        bNewPage = true;
                        bFirstPage = false;
                        bMorePagesToPrint = true;
                        break;
                    }
                    else
                    {
                        if (bNewPage)
                        {
                            //Draw Header
                            e.Graphics.DrawString("Acount Customer",
                                new Font(dataGridViewThietBi.Font, FontStyle.Bold),
                                Brushes.Black, e.MarginBounds.Left,
                                e.MarginBounds.Top - e.Graphics.MeasureString("Acount Customer",
                                new Font(dataGridViewThietBi.Font, FontStyle.Bold),
                                e.MarginBounds.Width).Height - 13);

                            String strDate = DateTime.Now.ToLongDateString() + " " +
                                DateTime.Now.ToShortTimeString();
                            //Draw Date
                            e.Graphics.DrawString(strDate,
                                new Font(dataGridViewThietBi.Font, FontStyle.Bold), Brushes.Black,
                                e.MarginBounds.Left +
                                (e.MarginBounds.Width - e.Graphics.MeasureString(strDate,
                                new Font(dataGridViewThietBi.Font, FontStyle.Bold),
                                e.MarginBounds.Width).Width),
                                e.MarginBounds.Top - e.Graphics.MeasureString("Acount Customer",
                                new Font(new Font(dataGridViewThietBi.Font, FontStyle.Bold),
                                FontStyle.Bold), e.MarginBounds.Width).Height - 13);

                            //Draw Columns                 
                            iTopMargin = e.MarginBounds.Top;
                            //foreach (DataGridViewColumn GridCol in dataGridViewtk.Columns)
                            //{
                            //    e.Graphics.FillRectangle(new SolidBrush(Color.LightGray),
                            //        new Rectangle((int)arrColumnLefts[iCount], iTopMargin,
                            //        (int)arrColumnWidths[iCount], iHeaderHeight));

                            //    e.Graphics.DrawRectangle(Pens.Black,
                            //        new Rectangle((int)arrColumnLefts[iCount], iTopMargin,
                            //        (int)arrColumnWidths[iCount], iHeaderHeight));

                            //    e.Graphics.DrawString(GridCol.HeaderText,
                            //        GridCol.InheritedStyle.Font,
                            //        new SolidBrush(GridCol.InheritedStyle.ForeColor),
                            //        new RectangleF((int)arrColumnLefts[iCount], iTopMargin,
                            //        (int)arrColumnWidths[iCount], iHeaderHeight), strFormat);
                            //    iCount++;
                            //}
                            for (int l = 0; l < dataGridViewThietBi.Columns.Count; l++)
                            {

                                e.Graphics.FillRectangle(new SolidBrush(Color.LightGray),
                                    new Rectangle((int)arrColumnLefts[iCount], iTopMargin,
                                    (int)arrColumnWidths[iCount], iHeaderHeight));

                                e.Graphics.DrawRectangle(Pens.Black,
                                    new Rectangle((int)arrColumnLefts[iCount], iTopMargin,
                                    (int)arrColumnWidths[iCount], iHeaderHeight));

                                e.Graphics.DrawString(dataGridViewThietBi.Columns[l].HeaderText,
                                    dataGridViewThietBi.Columns[l].InheritedStyle.Font,
                                    new SolidBrush(dataGridViewThietBi.Columns[l].InheritedStyle.ForeColor),
                                    new RectangleF((int)arrColumnLefts[iCount], iTopMargin,
                                    (int)arrColumnWidths[iCount], iHeaderHeight), strFormat);
                                iCount++;

                            }
                            bNewPage = false;
                            iTopMargin += iHeaderHeight;
                        }
                        iCount = 0;
                        //Draw Columns Contents                
                        //foreach (DataGridViewCell Cel in GridRow.Cells)
                        //{
                        //    if (Cel.Value != null)
                        //    {
                        //        e.Graphics.DrawString(Cel.Value.ToString(),
                        //            Cel.InheritedStyle.Font,
                        //            new SolidBrush(Cel.InheritedStyle.ForeColor),
                        //            new RectangleF((int)arrColumnLefts[iCount],
                        //            (float)iTopMargin,
                        //            (int)arrColumnWidths[iCount], (float)iCellHeight),
                        //            strFormat);
                        //    }
                        //    //Drawing Cells Borders 
                        //    e.Graphics.DrawRectangle(Pens.Black,
                        //        new Rectangle((int)arrColumnLefts[iCount], iTopMargin,
                        //        (int)arrColumnWidths[iCount], iCellHeight));
                        //    iCount++;
                        //}
                        for (int t = 0; t < GridRow.Cells.Count; t++)
                        {

                            if (GridRow.Cells[t].Value != null)
                            {
                                e.Graphics.DrawString(GridRow.Cells[t].Value.ToString(),
                                    GridRow.Cells[t].InheritedStyle.Font,
                                    new SolidBrush(GridRow.Cells[t].InheritedStyle.ForeColor),
                                    new RectangleF((int)arrColumnLefts[iCount],
                                    (float)iTopMargin,
                                    (int)arrColumnWidths[iCount], (float)iCellHeight),
                                    strFormat);
                            }
                            //Drawing Cells Borders 
                            e.Graphics.DrawRectangle(Pens.Black,
                                new Rectangle((int)arrColumnLefts[iCount], iTopMargin,
                                (int)arrColumnWidths[iCount], iCellHeight));
                            iCount++;

                        }
                    }

                    iRow++;
                    iTopMargin += iCellHeight;
                }
                //If more lines exist, print another page.
                if (bMorePagesToPrint)
                    e.HasMorePages = true;
                else
                    e.HasMorePages = false;
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message, "Error", MessageBoxButtons.OK,
                   MessageBoxIcon.Error);
            }
        }

        private void printDocument1_BeginPrint(object sender, System.Drawing.Printing.PrintEventArgs e)
        {
            try
            {
                strFormat = new StringFormat();
                strFormat.Alignment = StringAlignment.Near;
                strFormat.LineAlignment = StringAlignment.Center;
                strFormat.Trimming = StringTrimming.EllipsisCharacter;

                arrColumnLefts.Clear();
                arrColumnWidths.Clear();
                iCellHeight = 0;
                iCount = 0;
                bFirstPage = true;
                bNewPage = true;

                // Calculating Total Widths
                iTotalWidth = 0;
                //foreach (DataGridViewColumn dgvGridCol in dataGridViewtk.Columns)
                //{
                //    iTotalWidth += dgvGridCol.Width;
                //}
                for (int k = 0; k < dataGridViewThietBi.Columns.Count; k++)
                {
                    iTotalWidth += dataGridViewThietBi.Columns[k].Width - 12;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void textBoxXTim_KeyPress_1(object sender, KeyPressEventArgs e)
        {
            if (radioButtonTinhTrang.Checked == true)
            {
                if (!Char.IsDigit(e.KeyChar) && !Char.IsControl(e.KeyChar))
                    e.Handled = true;
            }
        }

        
    }
}
